import React, { use, useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import './StockChart.css';

//只有分时图 .2025年10月8日 确立为所用分时图
//组件的接口使用的是后端的数据结构，然后传送到这里自己分解成echarts的数据结构，再进行渲染
const TickChart = ({tickData,isDataLoaded,currentChartType='1day'}) => {

  const mainChartRef = useRef(null);
  const volumeChartRef = useRef(null);
  const mainChartInstance = useRef(null);
  const volumeChartInstance = useRef(null);

  const chartWrapperRef = useRef(null);
  const [tooltipData, setTooltipData] = useState(null);
  const [crosshairPosition, setCrosshairPosition] = useState(null);
  const [timeChartData, setTimeChartData] = useState(null);
  const timeChartDataRef = useRef(timeChartData);


  useEffect(() => {
    console.log('tickData = ',tickData)
    console.log('currentChartType = ',currentChartType)
    // 初始化图表
    if (mainChartRef.current) {
      // 如果已经有实例，先销毁
      if (mainChartInstance.current) {
        mainChartInstance.current.dispose();
      }
      // 创建新实例
      mainChartInstance.current = echarts.init(mainChartRef.current);
    }
    if(volumeChartRef.current)
    {
      if (volumeChartInstance.current) {
        volumeChartInstance.current.dispose();
      }
      volumeChartInstance.current = echarts.init(volumeChartRef.current);
    }

    if(tickData && tickData.data && tickData.data.length > 0)
    {
      renderTimeChart(); // 确保数据更新后立即渲染图表
    }
    
    // 组件卸载时销毁图表
    return () => {
      if (mainChartInstance.current) {
        mainChartInstance.current.dispose();
      }
    };
  }, [tickData,currentChartType,isDataLoaded]);
  
  // 窗口大小变化时，重新调整图表大小
  useEffect(() => {
    const handleResize = () => {
      if (mainChartInstance.current) {
        mainChartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

    // 同步更新 timeChartDataRef
  useEffect(() => {
    timeChartDataRef.current = timeChartData;
  }, [timeChartData]);

    // 更新分时图标签.minPrice：最低价，maxPrice：最高价，maxChange：最大涨幅，volumes：成交量数组，times：时间数组
    const updateTimeLabels = (minPrice, maxPrice, maxChange, pre_close,volumes, times) => {
      const priceLabels = document.getElementById('price-labels');
      const changeLabels = document.getElementById('change-labels');
      const volumeLabels = document.getElementById('volume-labels');
      const priceStepNum = 4;//大图使用9个区间，小图使用4个区间 
      
      if (priceLabels && changeLabels && volumeLabels) {
        priceLabels.innerHTML = '';
        changeLabels.innerHTML = '';
        volumeLabels.innerHTML = '';
        
        // 检查数据有效性
        if (!times || !volumes || times.length === 0 || volumes.length === 0) {
          console.warn('Invalid or empty data in updateTimeLabels');
          return;
        }

        // 计算最大涨幅和最大跌幅
        const priceStep = (maxPrice - minPrice) / (priceStepNum*2); // 上下各4个区间

        //从上到下（价格标签，右侧）
        for (let i = priceStepNum; i >= -priceStepNum; i--) {
          const price = pre_close + i * priceStep;
          const priceElement = document.createElement('div');
          priceElement.textContent = price.toFixed(2);
          priceElement.className = i === 0 ? 'zero-axis' : (i > 0 ? 'positive' : 'negative');
          priceLabels.appendChild(priceElement);
        }
        
        // 分时图涨跌幅标签（左侧）- 零轴上下各分为9个区间
        const changeRange = maxChange * 100;
        const changeStep = changeRange / priceStepNum;
        const labelHeight = 100 / (priceStepNum * 2); // 计算每个标签的高度百分比
        for (let i = priceStepNum; i >= -priceStepNum; i--) {
          const changePercent = i * changeStep;
          const changeElement = document.createElement('div');
          changeElement.textContent = changePercent.toFixed(2) + '%';
          changeElement.className = i === 0 ? 'zero-axis' : (i > 0 ? 'positive' : 'negative');
          // changeElement.style.position = 'absolute';
          // changeElement.style.top = `${50 + (i * labelHeight)}%`; // 动态计算位置
          // changeElement.style.transform = 'translateY(-50%)';
          changeLabels.appendChild(changeElement);
        }
        
        
        // 成交量标签（左侧）- 4个标签
        const maxVolume = Math.max(...volumes.map(v => v.value));
        const volumeStep = maxVolume / 3;
        for (let i = 3; i >= 0; i--) {
          const volume = i * volumeStep;
          const volumeElement = document.createElement('div');
          volumeElement.textContent = (volume / 10000).toFixed(1) + '万';
          volumeElement.style.color = '#ccc';
          volumeLabels.appendChild(volumeElement);
        }
      }
    };
    // 生成分时图网格配置
    const generateTimeGridLines = (minPrice, maxPrice, pre_close) => {
      const priceStepNum = 4;//大图使用9个区间，小图使用4个区间 
      const gridLines = [];
      const maxDiff = Math.max(Math.abs(minPrice - pre_close),Math.abs(maxPrice - pre_close))
      const priceStep = maxDiff / priceStepNum; // 9个区间
      
      // 生成9条水平网格线
      for (let i = 0; i <= priceStepNum*2; i++) {
        const price = pre_close -1.0 * maxDiff + i * priceStep;
        // console.log('price = ',price,basePrice)
        const isZeroLine = Math.abs(price - pre_close) < priceStep * 0.1;
        
        gridLines.push({
          y: price,
          lineStyle: {
            color: isZeroLine ? '#ff0000' : 'rgba(255, 0, 0, 0.3)',
            width: isZeroLine ? 2 : 1,
            type: isZeroLine ? 'solid' : 'dashed'
          }
        });
      }
      return gridLines;
    };
    // 生成时间网格线
    const generateTimeGridLinesVertical = (times) => {
      if(currentChartType === '1day'  )
      {
        if (!times || times.length === 0) return [];
        // 提取日期部分（假设 times[0] 的格式为 'YYYY-MM-DD HH:mm'）
        const datePart = times[0].split(' ')[0];
        const fixedTimes = ['10:00', '10:30', '11:00', '11:30', '13:30', '14:00', '14:30'];
        const gridLines = [];
        fixedTimes.forEach(time => {
          // 组合日期和时间
          const fullTime = `${datePart} ${time}`;
          let lineStyle = {
            color: 'rgba(255, 0, 0, 0.3)',
            type: 'dashed',
            width: 1
          };
          
          // 检查是否为整点或特定时间
          if (time === '10:30' || time === '14:00') {
            lineStyle.type = 'solid';
            lineStyle.width = 1;
          } else if (time === '11:30') {
            lineStyle.type = 'solid';
            lineStyle.width = 2;
          }
          
          gridLines.push({
            lineStyle,
            x: fullTime
          });
        });

        return gridLines;
      }
      
    };

    // 生成分时图成交量网格配置
    const generateTimeVolumeGridLines = (maxVolume) => {
      const gridLines = [];
      const volumeStep = maxVolume / 3; // 4个区间
      
      // 生成4条水平网格线
      for (let i = 0; i <= 3; i++) {
        const volume = i * volumeStep;
        gridLines.push({
          y: volume,
          lineStyle: {
            color: 'rgba(255, 0, 0, 0.3)',
            type: 'dashed',
            width: 1
          }
        });
      }
      
      return gridLines;
    };
  
    // 绘制分时图
    const renderTimeChart = () => {
      if (!tickData || !tickData.data || tickData.data.length === 0) {
        console.warn('tickData is not loaded yet');
        return;
      }
      console.log('tickData = ',tickData)
      let chartDataDict = {}
      if (currentChartType === '1day') {
        chartDataDict = convertTimeData('1day')
      }
      else if (currentChartType === '5day') {
        chartDataDict = convertTimeData('5day')
      }
      const { times = [], data = [], avgData = [], volumes = [], pre_close } = chartDataDict;
      setTimeChartData(chartDataDict)
      // 添加鼠标事件监听
      // 确保数据加载完成后再绑定事件
      if (times && times.length > 0) {
        mainChartRef.current.addEventListener('mousemove', handleChartMouseMove);
        mainChartRef.current.addEventListener('mouseleave', handleChartMouseLeave);
      }
      // 修复鼠标位置与十字星位置不重叠的问题

      
      if (!Array.isArray(times) || !Array.isArray(data) || !Array.isArray(avgData) || !Array.isArray(volumes)) {
        console.error('Invalid data format for time chart');
        return;
      }
      
      const priceChanges = data.map(price => Math.abs(price - pre_close) / pre_close);
      const maxChange = Math.max(...priceChanges);
      const maxPrice = pre_close * (1 + maxChange);
      const minPrice = pre_close * (1 - maxChange);

      const maxVolume = volumes.length > 0 ? Math.max(...volumes.map(v => v.value)) : 0;
      updateTimeLabels( minPrice, maxPrice,maxChange,pre_close,volumes, times);
      
      // 生成网格线
      const gridLines = generateTimeGridLines(minPrice, maxPrice, pre_close);
      const volumeGridLines = generateTimeVolumeGridLines(maxVolume);
       // 应用网格线到图表
      const gridLinesVertical = generateTimeGridLinesVertical(times);
      
      
      
      // 主图配置
      const mainOption = {
        backgroundColor: '#000000',
        animation: false,
        grid: {
          left: 0,
          right: 0,
          top: 10,
          bottom: 5,
          containLabel: false,
          backgroundColor: '#000000'
        },
        xAxis: {
          type: 'category',
          data: times,
          show: false,
          boundaryGap: false,
          axisLine: {
            show: true,
          },
          coordinateSystem: 'cartesian2d',
        },
        yAxis: {
          type: 'value',
          scale: true,
          show: true,
          min: minPrice,
          max: maxPrice,
          splitLine: { show: false },
          coordinateSystem: 'cartesian2d',
        },
        series: [
          {
            name: '分时',
            type: 'line',
            data: data,
            smooth: true,
            lineStyle: {
              color: '#FFFFFF',
              width: 2
            },
            itemStyle: {
              color: '#FFFFFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255, 255, 255, 0.3)' },
                { offset: 1, color: 'rgba(255, 255, 255, 0.05)' }
              ])
            },
            symbol: 'none'
          },
          {
            name: '均价',
            type: 'line',
            data: avgData,
            smooth: true,
            lineStyle: {
              color: '#FFFF00',
              width: 1
            },
            itemStyle: {
              color: '#FFFF00'
            },
            symbol: 'none'
          }
        ]
      };
      
      // 手动添加主图网格线
      gridLines.forEach((gridLine) => {
        mainOption.series.push({
          type: 'line',
          data: times.map(() => gridLine.y),
          lineStyle: gridLine.lineStyle,
          symbol: 'none',
          animation: false
        });
        
      });

// 将竖线添加到 series.markLine
      if (gridLinesVertical && gridLinesVertical.length > 0) {
        mainOption.series = mainOption.series || [];
        mainOption.series.push({
          type: 'line',
          markLine: {
            silent: true,
            label: {
              show: false,
              position:'middle',
            },
            symbol: 'none',
            lineStyle: {
              color: 'rgba(255, 0, 0, 0.3)',
              type: 'dashed',
              width: 1
            },
            data: gridLinesVertical.map(line => ({
              xAxis: line.x,
              lineStyle: line.lineStyle
            })),
            z: 10 // 确保竖线在上层
          }
        });
      }
      
      // 成交量图配置
      const volumeOption = {
        backgroundColor: '#000000',
        animation: false,
        grid: {
          left: 5,
          right: 5,
          top: 5,
          bottom: 5,
          containLabel: false,
          backgroundColor: '#000000'
        },
        xAxis: {
          type: 'category',
          data: times,
          axisLine: { 
            show: true,
            lineStyle: { color: '#666' }
          },
          axisTick: { show: false },
          axisLabel: { 
            show: true, 
            fontSize: 10,
            color: '#ccc'
          },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          show: false,
          min: 0,
          max: maxVolume,
          splitLine: { show: false }
        },
        series: [
          {
            name: '成交量',
            type: 'bar',
            data: volumes.map((volume, index) => ({
              value: volume.value,
              itemStyle: {
                color: index > 0 && data[index] >= data[index - 1] ? '#ff0000' : '#00ff00'
              }
            })),
            barWidth: '60%'
          }
        ]
      };
      
      // 手动添加成交量网格线
      volumeGridLines.forEach((gridLine) => {
        volumeOption.series.push({
          type: 'line',
          data: times.map(() => gridLine.y),
          lineStyle: gridLine.lineStyle,
          symbol: 'none',
          animation: false
        });
      });
      if(mainChartInstance.current)
      {
          mainChartInstance.current.clear()
          mainChartInstance.current.setOption(mainOption,true);
      }
      if(volumeChartInstance.current)
      {
          volumeChartInstance.current.clear()

          volumeChartInstance.current.setOption(volumeOption,true);
      }

    };

    
  // 从接口获取分时数据
  const convertTimeData = (day) => {
    try {
      const tickDataInner = JSON.parse(JSON.stringify(tickData));
      if(day==='1day')
      {
          tickDataInner.ts_code = tickData.ts_code;
          tickDataInner.data = tickData.data.slice(-241)
      }

      // console.log('tickDataInner',tickDataInner)
      if (tickDataInner && tickDataInner.data) {
        const times = tickDataInner.data.map(item => item.time);
        const data = tickDataInner.data.map(item => item.price);
        const avgData = tickDataInner.data.map(item => item.avg_price);
        const pre_close = tickDataInner.data[0]?.pre_close;  //获取昨日收盘价，也适用于5日分时
        const volumes = tickDataInner.data.map(item => ({
          value: item.vol,
          itemStyle: { color: item.price >= item.pre_close ? '#ff0000' : '#00ff00' }
        }));

        return { times, data, avgData, volumes, pre_close };
      }
      return { times: [], data: [], avgData: [], volumes: [],pre_close:0 };
    } catch (error) {
      console.error('获取分时数据失败:', error);
      return { times: [], data: [], avgData: [], volumes: [],};
    }
  };
  //还有点问题
  const handleChartMouseMove = (event) => {
      const rect = mainChartRef.current.getBoundingClientRect();
      const leftLabelBar = document.getElementById('change-labels');
      const leftLabelWidth = leftLabelBar ? leftLabelBar.offsetWidth : 0;
      const x = event.clientX - rect.left + leftLabelWidth;
      const y = event.clientY - rect.top;
      setCrosshairPosition({ x, y });
      
      // 根据图表类型显示不同的提示信息
      if (currentChartType === '1day' || currentChartType === '5day') {
         const currentTimeChartData = timeChartDataRef.current;
        if(currentTimeChartData)//确保无数据时候无响应
        {
          const { times = [], data = [], avgData = [], volumes = [],pre_close } = currentTimeChartData;
          if (!Array.isArray(times) || !Array.isArray(data) || !Array.isArray(avgData) || !Array.isArray(volumes)) {
            console.error('Invalid data format for time chart');
            return;
          }
          
          // 使用 echarts 的 convertFromPixel 方法获取时间点索引
          const pointInGrid = [x, y];
          const pointInChart = mainChartInstance.current.convertFromPixel('grid', pointInGrid);
          const timeValue = pointInChart[0];
          // console.log('timeValue',timeValue,pointInChart)
          
          // 计算 timeValue 对应的索引（假设 timeValue 范围是 14-254）
          const minValue = 14;
          const maxValue = 254;
          const normalizedValue = (timeValue - minValue) / (maxValue - minValue);
          let index = Math.round(normalizedValue * (times.length - 1));
          
          // 确保索引在有效范围内
          index = Math.max(0, Math.min(index, times.length - 1));
          
          if (index >= 0 && index < times.length) {
            const price = data[index];
            const avgPrice = avgData[index];
            const change = ((price - pre_close) / pre_close * 100).toFixed(2);
            setTooltipData({
              time: times[index],
              price: price.toFixed(2),
              avgPrice: avgPrice.toFixed(2),
              change: `${change}%`,
              changeValue: (price - pre_close).toFixed(2),
              type: 'time'
            });
          }
        }
      } 
    };

    const handleChartMouseLeave = () => {
      setCrosshairPosition(null);
      setTooltipData(null);
    };


  return (
    <div className="main-container">
      <div className="chart-wrapper" ref={chartWrapperRef}>
        {/* 十字准星线 */}
        {crosshairPosition && (
          <>
            <div 
              className="crosshair-line crosshair-vertical"
              style={{ left: crosshairPosition.x, top: 0 }}
            />
            <div 
              className="crosshair-line crosshair-horizontal"
              style={{ top: crosshairPosition.y, left: 0 }}
            />
          </>
        )}
        
        {/* 工具提示 */}
        {tooltipData && crosshairPosition && (
          <div 
            className="tooltip"
            style={{ 
              left: crosshairPosition.x + 10, 
              top: crosshairPosition.y + 10 
            }}
          >
            {
              <>
                <div className="tooltip-line"><strong>时间:</strong> {tooltipData.time}</div>
                <div className="tooltip-line"><strong>价格:</strong> {tooltipData.price}</div>
                <div className="tooltip-line"><strong>均价:</strong> {tooltipData.avgPrice}</div>
                <div className="tooltip-line"><strong>涨跌:</strong> {tooltipData.changeValue}</div>
                <div className="tooltip-line"><strong>涨幅:</strong> {tooltipData.change}</div>
              </>
            }
          </div>
        )}
        
        {/* 左侧标签 - 分时图显示涨跌幅，K线图隐藏 */}
        <div className="change-labels" id="change-labels">
          {/* 涨跌幅标签将通过JS动态生成 */}
        </div>
        
        <div className="chart-main">
          <div ref={mainChartRef} className="main-chart"></div>
          <div ref={volumeChartRef} className="volume-chart"></div>
        </div>
        
        {/* 右侧标签容器 */}
        <div style={{ display: 'flex', flexDirection: 'column', width: '80px' }}>
          {/* 价格标签 */}
          <div className="price-labels" id="price-labels">
            {/* 价格标签将通过JS动态生成 */}
          </div>
          
          {/* 成交量/成交金额标签 */}
          <div className="volume-labels" id="volume-labels">
            {/* 成交量标签将通过JS动态生成 */}
          </div>
        </div>
      </div>
   </div>        
  );
};

export default TickChart;